#!/usr/bin/python
import settings
import urllib2
import cookielib
import socket
import time

DEFAULT_USERAGENT = 'djwatchd.webchecks'

socket.setdefaulttimeout(settings.WEBCHECKS_TIMEOUT)
#socket.setdefaulttimeout(timeout)

def get_report():
    result = {}
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    for params in getattr(settings, 'WEBCHECKS', []):
        url = params.get('url')
        if not url:
            raise ValueError('incorrect check rule %s' % repr(params))

        name = params.get('name', url)

        req = urllib2.Request(url, params.get('post'))
        req.add_header('User-agent', params.get('useragent', DEFAULT_USERAGENT))
        req.add_header("Accept-Encoding", "gzip, deflate")  # traffic

        start = time.time()
        try:
            connection = opener.open(req)
        except urllib2.URLError:
            code = -1
            content = ''
        except urllib2.HTTPError, e:
            code = e.getcode()
            content = e.read()
        else:
            code = 200
            content = connection.read()

        result[name] = {
            'size': len(content),
            'code': code,
            'time': time.time() - start,
        }
    return result

if __name__ == '__main__':
    print get_report()
